const Post = require("../models/post");
const User = require("../models/user");
const Message = require("../models/message");
const sequelize = require("../config/sequelize");

//增加消息
exports.add = async function (
  content,
  userId,
  operatorId,
  type,
  postId,
  commentId
) {
  await Message.create({
    content,
    userId,
    operatorId,
    type,
    postId,
    commentId,
  });
};

//删除点赞消息
exports.delete = async function (operatorId, postId, type) {
  await Message.destroy({
    where: {
      operatorId,
      postId,
      type,
    },
  });
};

//删除评论消息
exports.deleteComment = async function (postId, commentId) {
  await Message.destroy({
    where: {
      postId,
      commentId,
    },
  });
};

//删除关注消息
exports.deleteFollow = async function (operatorId, userId, type) {
  await Message.destroy({
    where: {
      operatorId,
      userId,
      type,
    },
  });
};

//删除某篇文章下的所有消息
exports.deleteAll = async function (postId) {
  return Message.destroy({
    where: { postId },
  });
};

//获取消息列表
exports.getList = async function(userId,size,page){
  size = Number(size);
  page = Number(page);
  let {rows,count} = await Message.findAndCountAll({
      where:{userId},
      attributes:['id','content','userId','type','createdAt'],
      offset:(page-1) * size,
      limit:size,
      include:[
          {
              model:User,
              attributes: ['id', 'username','avatar'],
              as:'operator'
          },
          {
              model:Post,
              attributes:['id','content','imgs'],
              as:'post'
          }
      ],
      order:[['createdAt','DESC']]
  });

  rows.forEach(item => {
      if(item.type != 3)
          item.post.imgs = JSON.parse(item.post.imgs);
  });


  return {
      rows,count
  }
}

//获取该用户的未读消息数量
exports.getReadNum = async function (userId) { 
  let { count } = await Message.findAndCountAll({
      where:{
          userId,
          isRead: 0,
      },
      attributes:['id'],
  });
  return count;
}

//让未读消息变成已读
exports.readed = async function (userId) { 
  return await Message.update({ isRead: 1},{ 
      where:{
          userId
      },
      individualHooks:true
  });
}